package com.shinewind.info.controller;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HtmlUtil;
import com.shinewind.common.constant.messageConstant;
import com.shinewind.info.service.*;
import com.shinewind.pojo.dto.PageDto;
import com.shinewind.pojo.dto.UserDto;
import com.shinewind.pojo.entity.*;
import com.shinewind.pojo.result.Result;
import com.shinewind.pojo.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/userInfo")
@Api(value = "用户资料接口",description = "用于展示用户资料信息")
public class UserInfoController {
    @Autowired
    private IUserDetailService iUserDetailService;
    @Autowired
    private IArticleService iArticleService;
    @Autowired
    private IUserInfoService iUserInfoService;
    @Autowired
    private IUserRoleService iUserRoleService;
    @Autowired
    private IUserFollowService iUserFollowService;
    @Autowired
    private IUserSaveService iUserSaveService;
    @Autowired
    private ICommentService iCommentService;

    @GetMapping("/{mId}")
    @ApiOperation(value = "用户信息",notes = "用户信息",response = Result.class)
    public Result getUserInfoById(@PathVariable("mId") String mId){
        //根据模型id查询文章信息
        Article article = iArticleService.getArticleById(mId);
        //根据文章关联的用户id查询用户昵称
        UserInfo userInfo = iUserInfoService.getUserById(article.getUId());
        //根据文章关联的用户id查询用户资料
        UserDetail userDetail = iUserDetailService.getUserDetailById(article.getUId());
        UserDetailVo userDetailVo = UserDetailVo.builder().build();
        BeanUtils.copyProperties(userDetail,userDetailVo);
        userDetailVo.setNickName(userInfo.getNickName());
        //获取文章数、关注数、点赞数
        //1.文章数
        userDetailVo.setArticle(iArticleService.getArticleCountByUid(article.getUId()));
        //2.关注数
        userDetailVo.setFocus(iUserFollowService.getfIdCount(article.getUId()));
        //3.点赞数
        userDetailVo.setGood(iCommentService.getSumLoveByUid(article.getUId()));

        return Result.success(userDetailVo, BooleanUtil.isTrue(ObjectUtil.isNotNull(userDetailVo)),
                messageConstant.QUERY_SUCCESS);
    }

    @GetMapping("/username")
    //@PreAuthorize("hasAnyAuthority('ROLE_USER')")
    @ApiOperation(value = "按用户名查找用户",notes = "用户信息",response = Result.class)
    public Result getUserInfoByUsername(String username){
        //根据username查询用户
        UserInfo user = iUserInfoService.getUserInfoByUsername(username);
        return Result.success(user, BooleanUtil.isTrue(ObjectUtil.isNotNull(user)),
                messageConstant.QUERY_SUCCESS);
    }

    @GetMapping("/detail/{uId}")
    //@PreAuthorize("hasAnyAuthority('ROLE_USER')")
    @ApiOperation(value = "按用户id查找用户",notes = "用户信息",response = Result.class)
    public Result getUserInfoByUid(@PathVariable("uId") String uId){
        UserDetailVo userDetailVo = getUserDetailVo(uId);
        return Result.success(userDetailVo, BooleanUtil.isTrue(ObjectUtil.isNotNull(userDetailVo)),
                messageConstant.QUERY_SUCCESS);
    }

    private UserDetailVo getUserDetailVo(@PathVariable("uId") String uId) {
        //根据uid查询用户
        UserDetail user = iUserDetailService.getUserDetailById(uId);
        UserDetailVo userDetailVo = UserDetailVo.builder().build();
        BeanUtils.copyProperties(user,userDetailVo);
        //获取nickName
        userDetailVo.setNickName(iUserInfoService.getUserById(uId).getNickName());
        //1.文章数
        userDetailVo.setArticle(iArticleService.getArticleCountByUid(uId));
        //2.关注数
        userDetailVo.setFocus(iUserFollowService.getfIdCount(uId));
        //3.点赞数
        userDetailVo.setGood(iCommentService.getSumLoveByUid(uId));
        return userDetailVo;
    }

    @PostMapping("/follow/{uId}")
    @ApiOperation(value = "按用户id查找我的关注",notes = "关注信息",response = PageVo.class)
    public PageVo<UserFollowVo> getUserFollowByUid(@PathVariable("uId") String uId, @RequestBody PageDto pageDto){
        //根据uid查询所有被关注的用户
        List<String> userFollow = iUserFollowService.getfIdByuId(uId,pageDto);
        //根据被关注的用户id,查询其相关用户的信息
        List<UserFollowVo> userFollowVos = userFollow.stream().map(fId ->{
            UserFollowVo userFollowVo = UserFollowVo.builder().build();
            UserDetailVo userDetailVo = getUserDetailVo(fId);
            BeanUtils.copyProperties(userDetailVo,userFollowVo);
            return userFollowVo;
        }).collect(Collectors.toList());
        Integer total = Math.toIntExact(iUserFollowService.getfIdCount(uId));
        return new PageVo<UserFollowVo>(userFollowVos, BooleanUtil.isTrue(userFollowVos.size() > 0),
                messageConstant.QUERY_SUCCESS,total);
    }

    @GetMapping("/fans/{fId}")
    @ApiOperation(value = "按用户id查找我的粉丝",notes = "粉丝信息",response = Result.class)
    public Result getUserFansByUid(@PathVariable("fId") String fId){
        //根据uid查询所有粉丝用户
        List<String> userFollow = iUserFollowService.getuIdByfId(fId);
        //根据被关注的用户id,查询其相关用户的信息
        List<UserFollowVo> userFollowVos = userFollow.stream().map(uId ->{
            UserFollowVo userFollowVo = UserFollowVo.builder().build();
            UserDetailVo userDetailVo = getUserDetailVo(uId);
            BeanUtils.copyProperties(userDetailVo,userFollowVo);
            return userFollowVo;
        }).collect(Collectors.toList());
        return Result.success(userFollowVos, BooleanUtil.isTrue(userFollowVos.size() > 0),
                messageConstant.QUERY_SUCCESS);
    }

    @PostMapping("/save/{uId}")
    @ApiOperation(value = "按用户id查找我收藏的文章",notes = "收藏信息",response = PageVo.class)
    public PageVo<UserSaveVo> getUserSaveByUid(@PathVariable("uId") String uId, @RequestBody PageDto pageDto){
        //根据uid查询所有被收藏文章
        List<Integer> userSave = iUserSaveService.getaIdByuId(uId,pageDto);
        //根据被关注的文章id,查询其相关文章的信息
        List<UserSaveVo> userSaveVos = userSave.stream().map(aId ->{
            UserSaveVo userSaveVo = UserSaveVo.builder().build();
            //根据aid拿到mid，查询信息
            String mId = iArticleService.getArticleByAid(aId).getMId();
            Article article = iArticleService.getArticleById(mId);
            BeanUtils.copyProperties(article,userSaveVo);
            //处理content内容,只返回文字
            String content = article.getContent();
            //获取content中img的src属性
            Document document = Jsoup.parse(content);
            Elements imgs = document.getElementsByTag("img");
            List<String> imagesUrl = new ArrayList<>();
            for(Element img : imgs){
                if(StrUtil.isNotBlank(img.attr("src")))
                    imagesUrl.add(img.attr("src"));
            }
            userSaveVo.setImages(imagesUrl);
            //去除html标签
            content = HtmlUtil.cleanHtmlTag(article.getContent());
            //将转义字符还原
            content = HtmlUtil.unescape(content);
            userSaveVo.setContent(content);
            //查询用户昵称和头像
            userSaveVo.setNickName(iUserInfoService.getUserById(article.getUId()).getNickName());
            userSaveVo.setAvatar(iUserDetailService.getUserDetailById(article.getUId()).getAvatar());
            //设置关联的模型或新闻编号
            userSaveVo.setMId(article.getMId());
            return userSaveVo;
        }).collect(Collectors.toList());
        Integer total = Math.toIntExact(iUserSaveService.getaIdCount(uId));
        return new PageVo<UserSaveVo>(userSaveVos, BooleanUtil.isTrue(userSaveVos.size() > 0),
                messageConstant.QUERY_SUCCESS,total);
    }

    @PostMapping("/focus/user/{fId}/{uId}")
    @ApiOperation(value = "用户关注功能",notes = "用户关注",response = Result.class)
    public Result focusUser(@PathVariable("fId") String fId,@PathVariable("uId") String uId){
        String flag = iUserFollowService.focusUserByFidANDUid(fId,uId);
        if(flag == "关注成功")
            return Result.success(true, flag);
        else
            return Result.fail(false,flag);
    }

    @PostMapping("/cancel/focus/user/{fId}/{uId}")
    @ApiOperation(value = "用户取消关注功能",notes = "取消用户关注",response = Result.class)
    public Result cancelFocusUser(@PathVariable("fId") String fId,@PathVariable("uId") String uId){
        String flag = iUserFollowService.cancelFocusUserByFidANDUid(fId,uId);
        if(flag == "取消关注成功")
            return Result.success(true, flag);
        else
            return Result.fail(false,flag);
    }

    @PostMapping("/save/article/{aId}/{uId}")
    @ApiOperation(value = "用户文章收藏",notes = "文章收藏",response = Result.class)
    public Result saveArticleByuId(@PathVariable("aId") Integer aId,@PathVariable("uId") String uId){
        String flag = iUserSaveService.saveArticleByaIdANDuId(aId,uId);
        if(flag == "收藏成功")
            return Result.success(true, flag);
        else
            return Result.fail(false,flag);
    }

    @DeleteMapping("/save/delete/{aId}/{uId}")
    @ApiOperation(value = "删除收藏的文章",notes = "删除文章收藏",response = Result.class)
    public Result deleteMySaveArticle(@PathVariable("aId") Integer aId,@PathVariable("uId") String uId){
        Boolean flag = iUserSaveService.deleteSaveArticleByAidANDUid(aId,uId);
        if(flag){
            return Result.success(true,messageConstant.DELETE_SUCCESS);
        }
        else{
            return Result.fail(false,messageConstant.DELETE_ERROR);
        }
    }

    @PutMapping("/self/update/{uId}")
    @ApiOperation(value = "更改用户信息",notes = "更改资料",response = Result.class)
    public Result updateSelfInfo(@PathVariable("uId") String uId,@RequestBody UserDto userDto){
        String flag = iUserInfoService.updateUserInfoByDto(uId,userDto);
        if(flag == "修改个人资料成功"){
            return Result.success(true,flag);
        }
        else{
            return Result.fail(false,flag);
        }
    }
}